from Registry import Registry
import sqlite3, re

class Domains():
    db = None
    def __init__(self):
        self.db = sqlite3.connect("db.sqlite").cursor()

    def get_by_id(self, id):
        self.db.execute("SELECT * FROM domains WHERE id=1")
        id, ip_id, name, priority = self.db.fetchone()
        return {'id': id, 'ip_id': ip_id, 'name': name, 'priority': priority}

    def get_domain_id(self, project_id, id_or_name):
        if re.match('^[0-9]+$', id_or_name): #TODO перевести на is_numeric или типа того
            return self._get_by_id(project_id, id_or_name)
        else:
            return self._get_by_name(project_id, id_or_name)

    def _get_by_name(self, project_id, name):
        self.db.execute("SELECT d.id FROM projects p, ips i, domains d "\
                        "WHERE p.id = i.prj_id AND d.ip_id = i.id AND p.id = ?"\
                        "AND d.name = ?", (project_id, name))
        result = self.db.fetchone()
        return result[0] if result else None



    def _get_by_id(self, project_id, id):
        self.db.execute("SELECT d.id FROM projects p, ips i, domains d "\
                        "WHERE p.id = i.prj_id AND d.ip_id = i.id AND p.id = ?"\
                        "AND d.id = ?", (project_id, id))
        result = self.db.fetchone()
        return result[0] if result else None
